package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.repository.ApAssociateWordsRepository;
import com.heima.search.service.IApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements IApAssociateWordsService {

    @Autowired
    private ApAssociateWordsRepository repository;

    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if (dto==null || StringUtils.isEmpty(dto.getSearchWords().trim())){
            return ResponseResult.okResult();
        }

        Pageable page= PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"createdTime");
        List<ApAssociateWords> words = repository.findTopByAssociateWordsStartingWith(dto.getSearchWords(), page);

        return ResponseResult.okResult(words);
    }
}
